#!/usr/local/lsws/lsphp5/bin/php
<?php
namespace core;

include_once 'config/config.php';

//--------------------------------------------------
//          INITIALIZE
//--------------------------------------------------
function initialize()
{
    DB::query("create table if not exists Versioning(id int not null primary key auto_increment, migration int, branch varchar(255))");      
    
    DB::query("insert into Versioning values(null, 0, 'trunk')");
}

//--------------------------------------------------
//          GENERATE MODELS
//--------------------------------------------------
function generate_models()
{
    Model::generate_models();
} // end generate models

//--------------------------------------------------
//          HSS
//--------------------------------------------------
function hss()
{
    exec("./resource/bin/hss public/css/ploof.hss");
}

//--------------------------------------------------
//          UPDATE
//--------------------------------------------------
function setup_patch_directory($version= "trunk")
{
    if (opendir("resource/updates"))
        exec("rm -rf resource/updates");
    
    // export a copy of the code off the server:
    exec("mkdir resource/updates");
    if ($version != "trunk")
        $version= "branches/".$version;
    
    exec("svn export http://ploof.googlecode.com/svn/$version ./resource/updates/svn");
}

$patch_list= array(
        "./core"=>"./resource/updates/svn/core",
        "./config/config.default.php"=>"./resource/updates/svn/config/config.default.php",
        "./ploof"=>"./resource/updates/svn/ploof",
        "./public/index.php"=>"./resource/updates/svn/public/index.php",
        "./README"=>"./resource/updates/svn/README",
        "./config/fun.php"=>"./resource/updates/svn/config/fun.php",
        "./test/framework"=>"./resources/updates/svn/test/framework",
        "./public/js/ploof.js"=>"./resources/updates/svn/public/js/ploof.js"
    );
            
function generate_patch($version= "trunk")
{   
    global $patch_list; 
    setup_patch_directory($version);
    
    // build patch files:
    foreach($patch_list as $k=>$v)
    {
        $patch_filename= preg_replace("/[\.\/]*/", "_",$k);
        exec("diff -rupN -x .svn $k $v > ./resource/updates/$patch_filename.patch");
    }
}

function patch()
{
    global $patch_list;
    foreach($patch_list as $k=>$v)
    {
        $patch_filename= preg_replace("/[\.\/]*/", "_",$k);
        exec("patch -p1 < ./resource/updates/$patch_filename.patch");
    }
}

function update($version= "trunk")
{
    generate_patch($version);
    patch();
}
//--------------------------------------------------
//          MIGRATIONS
//--------------------------------------------------
function get_migration_path($branch)
{
    return "./resource/migrations/$branch";
}

function get_last_file_number_for($path)
{
    // input should be in the format:
    //  [number]__[text]
    foreach(scandir($path,1) as $k=>$v)
    {
        if ($v != "." and $v != "..")
            return $v; // scan dir (reverse order) then pop and split 
    }
}

function migration($branch= "trunk")
{
    $path= get_migration_path($branch);
    $dir= opendir($path);
    if (!$dir) 
    {
        mkdir($path);
        DB::query("insert into Versioning values(null, 0, '$branch');");
        touch($path."/1__Migration");
    }
    else
    {
        $last_number= get_last_file_number_for($path);
        touch($path."/".($last_number+1).PLOOF_SEPARATOR."Migration");
    }
}

function migrate($branch= "trunk")
{    
    $v= Versioning::find("branch= '".$branch."'");
    $last_db_number= $v->migration;
    $last_file_number= get_last_file_number_for(get_migration_path($branch));
    if ($last_db_number < $last_file_number)
    {
        // load them up and apply them!
        $path= get_migration_path($branch);
        $scan= scandir($path);
        foreach($scan as $k=>$v)
        {
            $split= explode("__", $v);
            $fnum= $split[0];
            print_r($fnum);
            print_r($last_db_number);
            if ($fnum > $last_db_number and $v != "." and $v != "..")
            {
                exec("cat ".$path."/".$v." | mysql -u ".DATABASE_USER." --password=".DATABASE_PASS." -h ".DATABASE_HOST." ".DATABASE_NAME);
            }
        } // end foreach
    } // end db_number vs file_number
}

//--------------------------------------------------
//          CLEAN
//--------------------------------------------------
function clean()
{
    exec("rm -rf resource/updates");
}

//--------------------------------------------------
//          PATCH PLOOF
//--------------------------------------------------
function patch_ploof($version= "trunk")
{
    global $patch_list;
    
    setup_patch_directory($version);

    exec("rm ./resource/updates/patch_ploof.patch");

    foreach($patch_list as $k=>$v)
    {
        exec("diff -rupN -x .svn $v $k >> ./resource/updates/patch_ploof.patch");
    }
    
    print "Please send ./resource/updates/patch_ploof.patch to frugalprogrammer@gmail.com!\n";
}

//--------------------------------------------------
//          TEST
//--------------------------------------------------
function test($lib='application')
{
    passthru('phpunit --bootstrap '.BASE_INSTALL.'/config/test_config.php test/'.$lib);
}

//--------------------------------------------------
//          MAIN LOOP
//--------------------------------------------------
if ($argc < 2)
{
    print "usage: ploof [command]\n\n";
    print "Commands: \n";
    print "test.................... run unit tests (application is default)\n";
    print "hss..................... recreate css from hss file\n";
    print "migrate................. migrate your database to the current migration\n";
    print "migration............... create a new migration in resource/migrations\n";
    print "generate_models......... generate classfiles from your database\n";
    print "initialize.............. initialize your database\n";
    print "update.................. update via diff; you can optionally supply a version to update to (trunk is default)\n";
    print "clean................... clean various detritus that can build up\n";
    print "migration............... create a migration; optionally add the branch for this migration\n";
    print "migrate................. bring this version of the database up to date; optionally add a branch to migrate from\n";
    print "patch_ploof............. for developers: create a patchfile to submit to patch ploof\n";
    exit;
}

print "Running ".$argv[1]."... \n";

($argc < 3) ? eval("core\\".$argv[1]."();") : eval("core\\".$argv[1]."('".$argv[2]."');");

?>
